package cn.ainit.sys.dz;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ainit.common.ReturnObject;
import cn.ainit.sys.dz.entity.DataListParamSa;
import cn.ainit.sys.dz.entity.DataListParamSf;
import cn.ainit.sys.dz.entity.SysDzColumns;
import cn.ainit.sys.dz.entity.SysDzReturnJson;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.menu.MenuController;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.DataGridReceiveParams;
import cn.ainit.sys.query.entity.QueryJson;

@Controller
@RequestMapping("/dz")
public class SysDzController {

	SysDzService sysDzService;
	@Resource
	public void setSysDzService(SysDzService sysDzService) {
		this.sysDzService = sysDzService;
	}

	@RequestMapping("/queryDz")
	@ResponseBody
	public QueryJson queryDzSource(DataGridReceiveParams recParam,String dzId, HttpServletRequest request){
		List<Object> list = new ArrayList<Object>();
		QueryJson queryJson = new QueryJson();
		try {
			SysDzSource dzSource = sysDzService.loadDzSource(dzId);
			if (dzSource != null || dzSource.getSqlText() != null) {
				QueryJson tmpQJ = sysDzService.queryDzSource(dzSource.getSqlText(),dzSource.getShowPk(),dzSource.getShowName(),recParam.getPage(),recParam.getRows());
				queryJson.setUrl("../dz/queryDz");
				queryJson.setRows(tmpQJ.getRows());
				queryJson.setTotal(tmpQJ.getTotal());
				queryJson.setPageNumber(recParam.getPage());
				queryJson.setPageSize(recParam.getRows());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}
	

	
	/*********************下述实现DzSource的增删改查************************************/
	//返回多个对照表信息
	//List  list.add(idObj)....
	@RequestMapping("/queryDzList")
	@ResponseBody
	public List<Object> queryDzSource(String dzIds,HttpServletRequest request){
		List<Object> list = new ArrayList<Object>();
		try {
			String[] dzId = dzIds.split(";");
			SysDzSource dzSource = null;
			for (int i = 0; i < dzId.length; i++) {
				if (dzId[i] != null && !dzId[i].equals("000") && !dzId[i].equals("")) {
					list.add(MenuController.mapList.get(dzId[i]));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	


	/***
	 * 加载单个的对照信息
	 * @param dzId
	 * @param filterSql
	 * @param request
	 * @return
	 * @author chenfeifei
	 * @version 创建时间：2014-12-16 下午05:34:42
	 */
	@RequestMapping("/queryDzData")
	@ResponseBody
	public List queryDzSource(String dzId,String filterSql,HttpServletRequest request){
		List list = new ArrayList();
		try {
			SysDzSource dzSource = null;
			if (dzId!= null && !dzId.equals("000") && !dzId.equals("")) {
				dzSource = sysDzService.loadDzSource(dzId);
			}else {
				dzSource = null;
			}
			if (dzSource != null && dzSource.getSqlText() != null) {
				list=sysDzService.queryDzSourceNoPage(dzSource.getSqlText(), dzSource.getShowPk(), dzSource.getShowName(), filterSql);
			}else{
				list=null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}



	/*****加载DataList字段*************************************/
	/**
	 * accurate  参数 意思为 查询时 是精确查询还是模糊查询   1为精确查询   0为 模糊查询
	 * @param seledRowsId 已经选中的行，前台每次都会传入，
	 * @param config 过滤条件   NAME-VAL2;NAME2-VAL2; ....
	 * inputCode:文本框得编码值
	 * inputVal：弹框查询条件封装的字段和值的拼接
	 */
	@RequestMapping("/loadDzDL")
	@ResponseBody
	public SysDzReturnJson loadDzDataList(String dzId,String dsId,String id,String inputVal,String inputCode,String filterConfig,HttpServletRequest request,
			String seledRowsId,String config) throws Exception{
		SysDzReturnJson queryJson = new SysDzReturnJson();
		DataListParamSa dataListParamSa=new DataListParamSa();
		DataListParamSf dataListParamSf=new DataListParamSf();
		//	ORDER BY (case CL_SOURCE_MANID when '"+yinchang+"' then null ELSE CL_SOURCE_MANID END) DESC
		try {
			List<SysDzColumns> list = sysDzService.colList(dzId, "");   //datagrid中的列要显示的列
			SysDzSource dzSource = sysDzService.loadDzSource(dzId);
			queryJson.setColumns(list);
			if (inputVal == null) {
				inputVal = "";
			}
			queryJson.setUrl(request.getContextPath()+"/dz/loadData");
			dataListParamSa.setDzId(dzId==null?"":dzId);
			dataListParamSa.setInputVal(inputVal);
			dataListParamSa.setConfig(config==null?"":config);
			dataListParamSa.setFilterConfig(filterConfig==null?"":filterConfig);
			dataListParamSa.setDsId(dsId);
			queryJson.setDataListParamSa(dataListParamSa);

			queryJson.setReturnColn(dzSource.getReturnCln());
			queryJson.setFunName(dzSource.getFunId());
			queryJson.setShowName(dzSource.getShowName());
			queryJson.setShowPk(dzSource.getShowPk());   //目前showPK和returnCln的返回的值一样
			queryJson.setDzId(dzSource.getDzId());
			queryJson.setDiyInterFaceFunc(dzSource.getDiyInterFaceFunc());
			//根据 获取所有的数据
			return queryJson;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

	@RequestMapping("/loadDzG")
	@ResponseBody
	public List loadDzG(String dzId,String clnName,HttpServletRequest request, HttpSession session){
		List list = new ArrayList();
		try {
			list = this.sysDzService.loadDzG(dzId,clnName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}


	
	/***
	 *  加载一对多的弹框的数据 
	 * @param dataGParams
	 * @param dsid			:弹框的dsid
	 * @param key			:弹框的外键的值
	 * @param coluname     	:弹框的列名
	 * @param filterConfig 	:加载数据之前从前台拼接好的sql(如普通弹框的过滤条件)
	 * @param config      	:弹框封装的筛选查询条件的
	 * @param request
	 * @return
	 */
	@RequestMapping("/loadMulEditData")
	@ResponseBody
	public QueryJson loadMulEditData(DataGridReceiveParams dataGParams,String dsid,String key,String coluname,String filterConfig,String config,HttpServletRequest request,HttpSession session){
		QueryJson queryJson = new QueryJson();
		try {
			List rows=new ArrayList();
			queryJson.setRows(rows);   
			//查找对照信息
			if(dsid==null||dsid.trim().equals("")||coluname==null||coluname.equals("")){
				throw new RuntimeException("[dsid="+dsid+",name="+coluname+"]");
			}
			SysColumns sysColumns = sysDzService.loadSysColumns(dsid,coluname);  //找到弹框字段一对多的配置信息
			if (sysColumns == null) {
				throw new RuntimeException("找不到此字段信息[dsid="+dsid+",name="+coluname+"]");
			}

			StringBuffer sql = new StringBuffer();
			//一对多的相似的dsid
			String mulSameDsId=sysColumns.getMultiSameDsid();  
			//一对多表的外建名
			String mulPk=sysColumns.getMultiClnsFk();  
			//获取一对多表的dsId
			String mulDsid=sysColumns.getMultiDzDsId();  
			//找到一对多那张表对应的datastore
			DataStore multiDataStore = sysDzService.getDataStore(mulDsid); 
			if (multiDataStore == null || "".equals(multiDataStore.getSqlText())) {
				throw new RuntimeException("没有配置一对多DSID信息");
			}
			List<SysColumns> mulColns=sysDzService.getMulConl(mulDsid);    //获取一对多那张表的columns 中的配置
			//查询表中那个字段配置了edittype 
			
			Set<String> dzColns=new HashSet<String>();  //存需要转译的字段集合
			Set<String> sysColns=new HashSet<String>();   //存不需要转译的字段集合
			List<SysColumns> moreShowColns=new ArrayList<SysColumns>();   //除了必须要显示的字段之外的还需显示的列
			List<SysColumns> quclnColns=new ArrayList<SysColumns>();   //弹框上显示的查询条件的列集合
			for (int i = 0; i < mulColns.size(); i++) {
				if("T".equals(mulColns.get(i).getIsshow())&&!"T".equals(mulColns.get(i).getHidden())&&"T".equals(mulColns.get(i).getCommonUse())&&mulColns.get(i).getEdiType()!=null&&mulColns.get(i).getEdiType()!=""){
					quclnColns.add(mulColns.get(i));
				}
				if("T".equals(mulColns.get(i).getIsshow()) && (mulColns.get(i).getHidden()==null||"".equals(mulColns.get(i).getHidden())||"F".equals(mulColns.get(i).getHidden())||"null".equals(mulColns.get(i).getHidden()))&&!mulColns.get(i).getName().equals(sysColumns.getMultiClnsDValue())){
					moreShowColns.add(mulColns.get(i));
				}
				if (mulColns.get(i).getFormatCont()!=null&&!"".equals(mulColns.get(i).getFormatCont())) {
					dzColns.add(mulColns.get(i).getName());
				}else {
					sysColns.add(mulColns.get(i).getName());
				}
			}
			//查询获取所有的选中的行      
			sql.append("select * from ("+multiDataStore.getSqlText()+") temp where "+mulPk+" = '"+key+"' and ds_id='"+(mulSameDsId==null||"".equals(mulSameDsId.trim())?dsid:mulSameDsId)+"'");
			//得到已选的行
			System.out.println("===================查询一对多已经选中的行："+sql.toString());
			queryJson.setRows(sysDzService.queryOldRowsBySql(sql.toString())); 
			
			
			//查询除了选中行外的所有所有数据
			List othList = new ArrayList();
			String morwScolnSql=" ";
			for (int i = 0; i < moreShowColns.size(); i++) {
					morwScolnSql+=" ,"+moreShowColns.get(i).getName()+" ";
			}
			
			//弹框的筛选条件拼接（不需要转义的字段）
			if(config != null && !"".equals(config.trim())){
				String[] allConfig=config.split(";");
				for (int i = 0; i < allConfig.length; i++) {
					if(allConfig[i]!=null&&allConfig[i].trim()!=""){
						String configName=allConfig[i].split("-")[0];
						if(sysColns.contains(configName)){
							String configVal=allConfig[i].split("-")[1];
							sql.append(" and "+configName.trim()+" like '%"+configVal.trim()+"%'");
						}
					}
				}
			}
			
			System.out.println("=====================一对多弹框的配置不全：dsid为"+dsid+"字段名称为:"+sysColumns.getEdiType()+"未配置");
			if (sysColumns.getEdiType() != null && !("".equals(sysColumns.getEdiType()))&&!"000".equals(sysColumns.getEdiType())&&!"nvl".equals(sysColumns.getEdiType().trim())) {
				//加载对照表信息
				SysDzSource dzSource = sysDzService.loadDzSource(sysColumns.getEdiType());   //加载对照表中的除了选中行的所有的信息
				//弹框的数据权限
				//获取当前登录人 ,dsId,dzId 
				String rightSql="";
				if(dsid!=""){
					rightSql=sysDzService.loadDzDataRight(sysColumns.getEdiType(), dsid,session, "");
				}
				String dzSql ="select * from ("+dzSource.getSqlText()+") QUERYTMP where 1 = 1 "+rightSql;
				StringBuffer sqlo = new StringBuffer(" SELECT ");
				sqlo.append(dzSource.getShowPk()+" "+ sysColumns.getMultiClnsDValue()+" FROM ("+dzSql+") A ");
				sqlo.append(" where "+ dzSource.getShowPk() + " not in ( select "+ sysColumns.getMultiClnsDValue()+ " from " + sysColumns.getMultiClnsTable() +" ");
				sqlo.append(" where "+sysColumns.getMultiClnsFk() +" = '"+key+"')");
				//弹框的筛选条件
				if(config != null && !"".equals(config.trim())){
					String[] allConfig=config.split(";");
					for (int i = 0; i < allConfig.length; i++) {
						if(allConfig[i]!=null&&allConfig[i].trim()!=""){
							String configName=allConfig[i].split("-")[0];
							if(dzColns.contains(configName.trim())){
								String configVal=allConfig[i].split("-")[1];
								sqlo.append(" and "+dzSource.getShowName()+" like '%"+configVal.trim()+"%'");
							}
						}
					}
				}
				if(filterConfig!=null&&!"".equals(filterConfig)){
					sqlo.append(filterConfig);
				}
				System.out.println("=============================一对多查询对应的slq:"+sqlo);
				othList = this.sysDzService.queryOldRowsBySql(sqlo.toString());
			}
			//包括选中的和非选中的所有的
			if(othList!=null&&othList.size()>0){
				queryJson.getRows().addAll(othList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}



	/******
	 * dzDataStore 中sql加载数据(普通弹框用到了)
	 * @param dataGParams
	 * @param filterConfig :加载数据之前从前台拼接好的sql(如普通弹框的过滤条件)
	 * @param dzId  
	 * @param config  :目前没有用到的参数
	 * @param inputVal ：弹框封装的筛选查询条件的
	 * @param inputCode:文本框的编码
	 * @param request
	 * @return
	 */
	@RequestMapping("/loadData")
	@ResponseBody
	public  SysDzReturnJson  queryPlanTopic(DataGridReceiveParams dataGParams,String dzId,String dsId,String filterConfig,String inputCode,String inputVal,String config,HttpServletRequest request,HttpSession session){
		SysDzReturnJson queryJson = new SysDzReturnJson();
		try {
			if(dsId==null){
				dsId="";
			}
			List rows=new ArrayList();
			queryJson.setRows(rows);   
			queryJson.setTotal(0);   
			SysDzSource dzSource = sysDzService.loadDzSource(dzId);
			//弹框的数据权限
			//获取当前登录人 ,dsId,dzId 
			String rightSql="";
			String anthorSql="";
			if(dsId!=""){
				rightSql=sysDzService.loadDzDataRight(dzId, dsId, session, "");
				anthorSql=sysDzService.loadDzAnotherPast(dzId, dsId);
			}
			String returnColn=dzSource.getReturnCln();
			if (dzSource != null) {
				StringBuffer sqlBuffer = new StringBuffer("select * from ("+dzSource.getSqlText()+anthorSql+") QUERYTMP where 1 = 1 "+rightSql);
				//以后要区分类别，目前主要采用的都是模糊查询
				if(inputVal!=null &&!inputVal.equals("null")&& !inputVal.isEmpty() && !"null".equals(inputVal) && !"".equals(inputVal)){   //弹框的刷选条件
					//:MAN_TYPE-111;M_NAME-222;
					String[] allConfig=inputVal.split(";");
					for (int i = 0; i < allConfig.length; i++) {
						if(allConfig[i]!=null&&allConfig[i].trim()!=""){
							String configName=allConfig[i].split("-")[0];
							String configVal=allConfig[i].split("-")[1];
							sqlBuffer.append(" and "+configName.trim()+" like '%"+configVal.trim()+"%'");
						}
					}
				}
				//已经拼接好的条件直接拼接在原sql上
				if(filterConfig!=null&&!filterConfig.equals("null")&&!"".equals(filterConfig.trim())){
					sqlBuffer.append(" and "+filterConfig);
				}
				String finalSql = sqlBuffer.toString().replace("$dsid", dsId);

				if(inputCode!=null&&inputCode!=""){
					String sqlCt=" ORDER BY ( case "+returnColn;
					String[] codes=inputCode.split(";");
					if(codes.length>0){
						for (int i = 0; i < codes.length; i++) {
							sqlCt+=" when '"+codes[i]+"' then null ";
							if(i==codes.length-1){
								sqlCt+=" ELSE "+returnColn+" END) DESC ";
							}
						}
					}
					finalSql="select * from ("+finalSql+") t "+sqlCt;
				}
				System.out.println("#357 sysDzController 中弹框（和其他空间）加载数据的sql："+finalSql);
				queryJson.setRows(sysDzService.queryOldRowsBySql(finalSql));       //不带分页的查询
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}

	/******
	 * dzDataStore 加载普通弹框的选中数据
	 * @param dataGParams
	 * @param dzId  
	 * @param inputCode:文本框的编码
	 * @param request
	 * @return
	 */
	@RequestMapping("/loadSelData")
	@ResponseBody
	public  SysDzReturnJson  loadSelData(DataGridReceiveParams dataGParams,String dzId,String inputCode,HttpServletRequest request){
		SysDzReturnJson queryJson = new SysDzReturnJson();
		try {
			List rows=new ArrayList();
			queryJson.setRows(rows);   
			SysDzSource dzSource = sysDzService.loadDzSource(dzId);
			if (dzSource != null) {
				StringBuffer sqlBuffer = new StringBuffer("select * from ("+dzSource.getSqlText()+") QUERYTMP where 1 = 1  ");
				//1.加载选中的数据(只有第一页的时候记载以选中的数据)
				if (inputCode!=null&&!"".equals(inputCode.trim())&&inputCode!=null&&inputCode.split(";")[0]!=null&&!inputCode.split(";")[0].equals("")) {
					String[] codeVal=inputCode.split(";");
					sqlBuffer.append("and "+dzSource.getReturnCln().trim()+" ='"+codeVal[0]+"'");
					rows=sysDzService.queryOldRowsBySql(sqlBuffer.toString());
					queryJson.setRows(rows);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return queryJson;
	}



	@RequestMapping("/getDsData")
	@ResponseBody
	public DataStore getDsInfo(String dzId,HttpServletRequest request) throws Exception{
		DataStore dataStore = new DataStore();
		try {
			SysDzSource sysDzSource = this.sysDzService.loadDzSource(dzId);
			String dsId = sysDzSource.getDsId();
			dataStore = sysDzService.getDataStore(dsId);
			if(dataStore != null){
				return dataStore;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}





	@RequestMapping("/loadBjCodeId")
	@ResponseBody
	public ReturnObject loadBjCodeId(String comparisonId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject=new ReturnObject();
		String newCodeId=sysDzService.getBjDzCodeId(comparisonId);
		returnObject.setInfo(newCodeId);
		return returnObject;
	}


	@RequestMapping("/loadFxCodeId")
	@ResponseBody
	public ReturnObject loadFxCodeId(String comparisonId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject=new ReturnObject();
		String newCodeId=sysDzService.getFxDzCodeId(comparisonId);
		returnObject.setInfo(newCodeId);
		return returnObject;
	}


	@RequestMapping("/loadCwCodeId")
	@ResponseBody
	public ReturnObject loadCwCodeId(String comparisonId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject=new ReturnObject();
		String newCodeId=sysDzService.getCwDzCodeId(comparisonId);
		returnObject.setInfo(newCodeId);
		return returnObject;
	}
}
